package com.hlyue.ingress.consecutiveportalhacking;

import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.util.Log;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Richard on 2015/8/27.
 */
public class UsageStateUtils {
    private final static String TAG = UsageStateUtils.class.getName();

    public static String getLastPackage(final Context context) {
        @SuppressWarnings("ResourceType") UsageStatsManager manager = (UsageStatsManager) context.getSystemService("usagestats");
        long ts = System.currentTimeMillis();
        List<UsageStats> usageStats = manager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, ts - 3000, ts);
        long lastTime = 0;
        String pkg = null;
        if (usageStats.size() != 0) {
            for (UsageStats stat : usageStats) {
                if (stat.getLastTimeUsed() > lastTime) {
                    lastTime = stat.getLastTimeUsed();
                    pkg = stat.getPackageName();
                }
            }
        }
        return pkg;
    }
}
